package com.henghai.zhenxuan.ui.page.mine;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.R;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.UpdateUserRequester;
import com.henghai.zhenxuan.domain.request.UploadAvatarRequester;
import com.henghai.zhenxuan.domain.request.UserInfoRequester;
import com.henghai.zhenxuan.lib.GlideEngine;
import com.henghai.zhenxuan.utils.MainHandler;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class SelfInfoFragment extends BaseFragment {
    private SelfInfoStates mStates;
    private UploadAvatarRequester mUploadFileRequester;
    private UpdateUserRequester mUpdateUserRequester;
    private UserInfoRequester mUserInfoRequester;
    private PageMessenger mMessenger;

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(SelfInfoStates.class);
        mUploadFileRequester = getFragmentScopeViewModel(UploadAvatarRequester.class);
        mUpdateUserRequester = getFragmentScopeViewModel(UpdateUserRequester.class);
        mUserInfoRequester = getActivityScopeViewModel(UserInfoRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mStates.avatar.set(AppConfig.INSTANCE.getMConfigs().user().get().getAvatar());
        mStates.name.set(AppConfig.INSTANCE.getMConfigs().user().get().getNickName());
        mStates.phone.set(AppConfig.INSTANCE.getMConfigs().user().get().getPhonenumber());

        mUserInfoRequester.getTokenResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(dataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            AppConfig.INSTANCE.getMConfigs().user().set(dataResult.getResult().getData());
            mMessenger.input(new Messages(Messages.EVENT_USERINFO_SUCCESS));
        });
        mUpdateUserRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            mUserInfoRequester.request(this);
            TipDialog.show("修改成功", WaitDialog.TYPE.SUCCESS);
            MainHandler.INSTANCE.postDelay(1500, () -> nav().navigateUp());
        });

        mUploadFileRequester.getUploadFileResult().observe(this, httpBeanDataResult -> {
            WaitDialog.dismiss();
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            if (httpBeanDataResult.getResult().getImgUrl() == null || httpBeanDataResult.getResult().getImgUrl().isEmpty()) {
                TipDialog.show("修改失败");
                return;
            }
            Log.d("song", "onViewCreated: "+httpBeanDataResult.getResult().getImgUrl());
            mStates.avatar.set(httpBeanDataResult.getResult().getImgUrl());
            AppConfig.INSTANCE.getMConfigs().user().get().setAvatar(httpBeanDataResult.getResult().getImgUrl());
            mMessenger.input(new Messages(Messages.EVENT_USERINFO_SUCCESS));
        });
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.fragment_self_info, BR.vm, mStates)
                .addBindingParam(BR.listener,new ListenerHandler())
                .addBindingParam(BR.click, new SelfInfoFragment.ClickProxy())
                .addBindingParam(BR.listener, new ListenerHandler());
    }

    public class ClickProxy {
        public void update() {
            if (mStates.name.get().isEmpty()) {
                TipDialog.show("请输入昵称", WaitDialog.TYPE.WARNING);
            }
            mUpdateUserRequester.request(getViewLifecycleOwner(), mStates.avatar.get(), mStates.name.get());
        }

        public void image() {
            ArrayList<CharSequence> list = new ArrayList<>();
            list.add("从相册选择");
            list.add("相机拍照");
            BottomMenu.show(list)
                    .setTitle("更换头像")
                    .setOnMenuItemClickListener((dialog, text, index) -> {
                        if (index == 0) {
                            PictureSelector.create(getContext())
                                    .openGallery(SelectMimeType.ofImage())
                                    .setImageEngine(GlideEngine.createGlideEngine())
                                    .setMaxSelectNum(1)
                                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                                        @Override
                                        public void onResult(ArrayList<LocalMedia> result) {
                                            Luban.with(getContext())
                                                    .load(new File(result.get(0).getRealPath()))
                                                    .setTargetDir(Const.COVER_PATH)
                                                    .ignoreBy(100)
                                                    .setFocusAlpha(false)
                                                    .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                                                    .setCompressListener(new OnCompressListener() {
                                                        @Override
                                                        public void onStart() {
                                                        }

                                                        @Override
                                                        public void onSuccess(File file) {
                                                            mStates.avatar.set(file.getPath());
                                                            mUploadFileRequester.request(getViewLifecycleOwner(), file);
                                                        }

                                                        @Override
                                                        public void onError(Throwable e) {
                                                            // 压缩失败
                                                        }
                                                    }).launch();
                                        }

                                        @Override
                                        public void onCancel() {

                                        }
                                    });
                        } else if (index == 1) {
                            PictureSelector.create(getContext())
                                    .openCamera(SelectMimeType.ofImage())
                                    .forResultActivity(new OnResultCallbackListener<LocalMedia>() {
                                        @Override
                                        public void onResult(ArrayList<LocalMedia> result) {
                                            Log.d("debug", "onResult: " + result.get(0).getRealPath());
                                            Luban.with(getContext())
                                                    .load(new File(result.get(0).getRealPath()))
                                                    .setTargetDir(Const.COVER_PATH)
                                                    .ignoreBy(100)
                                                    .setFocusAlpha(false)
                                                    .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                                                    .setCompressListener(new OnCompressListener() {
                                                        @Override
                                                        public void onStart() {
                                                        }

                                                        @Override
                                                        public void onSuccess(File file) {
                                                            mStates.avatar.set(file.getPath());
                                                            mUploadFileRequester.request(getViewLifecycleOwner(), file);
                                                        }

                                                        @Override
                                                        public void onError(Throwable e) {
                                                            // 压缩失败
                                                        }
                                                    }).launch();
                                        }

                                        @Override
                                        public void onCancel() {

                                        }
                                    });
                        }
                        return false;
                    });
        }

        public void name() {
            InputDialog.show("修改姓名", mStates.name.get(), "确定", "取消");
        }

    }


    public class ListenerHandler implements OnTitleBarListener {
        @Override
        public void onLeftClick(TitleBar titleBar) {
            OnTitleBarListener.super.onLeftClick(titleBar);
            nav().navigateUp();
        }

        @Override
        public void onRightClick(TitleBar titleBar) {
            OnTitleBarListener.super.onRightClick(titleBar);
        }
    }

    public static class SelfInfoStates extends StateHolder {
        public final State<String> name = new State<>("");
        public final State<String> phone = new State<>("");

        public final State<String> avatar = new State<>("");

    }

}
